/* * Copyright (c) 2012-2014 Kaarle Ritvanen * See LICENSE file for license details */ define( [ "acf2/dom", "acf2/statusbar", "acf2/type", "acf2/widget/abstract/fields", "jquery", "underscore", "jquery-ui/sortable" ], function(dom, statusBar, type, Base, $, _) { return Base.extend({ wrap: function() { return $("
").html(this.el); }, appendAboveFields: function(data, meta) { this.div = $("
"); this.el.append(this.div); var self = this; if (meta.type == "model") _.each(meta.actions, function(action) { self.div.append($("").attr( {type: "submit", value: action["ui-name"]} ).click(function() { data.invoke(action.name) .done(function() { alert("Done"); }) .fail(function() { alert("Failed"); }); })); }); }, appendBelowFields: function(data, meta) { if (meta.editable && _.contains(["collection", "list"], meta.type)) { if (!this.table) this.makeSortable(this.div); var self = this; var keys = _.clone(_.keys(data.data)); var button = $("").attr( {type: "submit", value: "Insert"} ).click(function() { var getter; function insert() { var name = getter(); if (_.contains(keys, name)) { button.prop("class", null); return; } keys.push(name); data.set( name, type.isTreeNode(meta.members) ? {} : null ).done(function(txnValid) { if (_.isObject(meta.removable)) meta.removable = []; meta.removable.push(name); self.renderCollectionMember(name, meta); button.prop("class", null); statusBar.validationReady(txnValid); }); } button.prop("class", "hidden"); if (meta.type == "collection") { var field = $("").attr({type: "text"}); var row = $("").html($("").html(field)); getter = function() { var res = field.val(); row.remove(); return res; } field.change(insert); self.appendRow(row); } else { getter = function() { return data.data.length + 1; }; insert(); } }); this.el.append($("

").html(button)); } }, appendWidget: function(el, label) { var self = this; el = dom.makeRow(el); if (el.is("tr")) { el.prepend($("").text(label)); this.appendRow(el); } else { if (el.is("table")) { this.makeSortable(el.find("tbody")); var td; el.find("tr").each(function(index, row) { td = $(""); $(row).prepend(td); }); td.text(label); this.table = el; } else this.table = null; this.div.append(el); } return el; }, appendRow: function(row) { if (!this.table) { this.table = this.makeSortable($("")); this.div.append($("").html(this.table)); } this.table.append(row); }, makeSortable: function(el) { var data = this.reqData; if (data.meta.type == "list") el.sortable({ start: function(event, ui) { $(":focus").change(); ui.item.data("index", ui.item.index()); }, stop: function(event, ui) { var oldIndex = ui.item.data("index") + 1; var newIndex = ui.item.index() + 1; if (newIndex != oldIndex) data.move(oldIndex, newIndex) .done(function(txnValid) { $("#content").trigger("reload", [txnValid]); }); } }); return el; } }); } );