diff options
Diffstat (limited to 'web/widget/field.js')
-rw-r--r-- | web/widget/field.js | 109 |
1 files changed, 109 insertions, 0 deletions
diff --git a/web/widget/field.js b/web/widget/field.js new file mode 100644 index 0000000..e4524e1 --- /dev/null +++ b/web/widget/field.js @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2012-2014 Kaarle Ritvanen + * See LICENSE file for license details + */ + +define( + [ + "acf2/error", + "acf2/statusbar", + "acf2/widget/abstract/base", + "jquery", + "underscore" + ], + function(formatError, statusBar, Base, $, _) { + var Class = Base.extend({ + init: function( + data, name, meta, level, editable, removable + ) { + this.editable = editable && meta.editable; + + var el = this.super( + Class, + "init", + data, + name, + meta, + level, + editable, + removable + ); + + if (this.editable) + this.field.change(_.bind(this.validateChange, this)); + + return el; + }, + + staticRender: function(value, meta) { + return $("<td>").text(value); + }, + + makeEl: function() { + this.super(Class, "makeEl"); + if (!this.field) this.field = this.el; + }, + + createEl: function() { return $("<input>"); }, + + render: function(value, meta) { + this.field.attr({type: "text", value: value}); + }, + + wrap: function() { + var td = $("<td>"); + this.msg = $("<div>"); + td.append(this.msg); + td.append(this.el); + return td; + }, + + validate: function(value) { + this.super(Class, "validate", value); + if (!this.visible || !this.editable) return; + this.validateChange(); + }, + + validateChange: function() { + this.msg.text("[checking]"); + statusBar.setError("Validating changes", "validate"); + + var self = this; + + this.data.set(this.name, this.get()) + .done(function(txnValid) { + self.msg.empty() + self.setStatus(self.data.status(self.name)); + statusBar.validationReady(txnValid); + self.el.trigger("validated"); + + }) + .fail(function(xhr) { + if (_.isString(xhr)) self.msg.text(xhr); + + else if (xhr.statusCode().status == 422) + self.msg.html( + _.reduce( + _.map( + $.parseJSON(xhr.responseText), _.escape + ), + function(a, b) { return a + "<br/>" + b; } + ) + ); + + else self.msg.text(formatError("Error", xhr)); + + self.setStatus("invalid"); + statusBar.validationReady(false); + }); + }, + + get: function() { + return this.editable ? + (this.field.val() || null) : this.data.get(this.name); + } + }); + + return Class; + } +); |