Wednesday, 7 August 2013

How to implement editable text in Meteor and DRY?

How to implement editable text in Meteor and DRY?

I have come up with a methodology for making editable text in my Meteor
app. However, it does not follow the DRY paradigm and I'd like to change
that but I am not too good with Javascript yet...
Suppose I have a table cell with some text and I'd like to double click it
to edit it. I created a template variable to handle this:
<td class="itemName">


<input class="editItemName" type="text" value="{{name}}"
style="width:100px;">
{{/unless}}
</td>
I then create an event to execute this transition on a double-click:
Template.inventoryItemDetail.events = {
'dblclick td.itemName': function (evt) {
Session.set("editItemName",true);
},
'blur input.editItemName': function () {
Session.set("editItemName",null);
},};
I also reused the ok_cancel code from the ToDo's example app (but that's
sort of irrelevant):
// Returns an event_map key for attaching "ok/cancel" events to
// a text input (given by selector)
var okcancel_events = function (selector) {
return 'keyup '+selector+', keydown '+selector+', focusout '+selector;
};
// Creates an event handler for interpreting "escape", "return", and "blur"
// on a text field and calling "ok" or "cancel" callbacks.
var make_okcancel_handler = function (options) {
var ok = options.ok || function () {};
var cancel = options.cancel || function () {};
return function (evt) {
if (evt.type === "keydown" && evt.which === 27) {
// escape = cancel
cancel.call(this, evt);
evt.currentTarget.blur();
} else if (evt.type === "keyup" && evt.which === 13) {
// blur/return/enter = ok/submit if non-empty
var value = String(evt.target.value || "");
if (value) {
ok.call(this, value, evt);
evt.currentTarget.blur();
}
else {
cancel.call(this, evt);
evt.currentTarget.blur();
}
}
};
};
Template.inventoryItemDetail.events[ okcancel_events('input.editItemName')
] = make_okcancel_handler({
ok: function (value) {
Items.update(this._id, {$set: {name: value}});
}
});
Finally, I have to tie this Session variable to the template variable:
Template.inventoryItemDetail.editItemName = function () {
return Session.get("editItemName");
};
So right now, I have repeated all of this again and again for each
editable text field and it all works, but it seems like terribly
programming practice. I have found various editable text utilities on
Github but I don't entirely understand them and none of them are for
Meteor!
I'd really like to expand my knowledge of Meteor and Javascript by
creating a tool that allows me to have editable text without repeating
myself this ridiculous amount for each editable text field.
Thanks,
Chet

No comments:

Post a Comment