There is a page showing a list of objects (eg books). This list can programmatically increase through client-side interaction. Which is a good way to create new "books" in the DOM?
I'd like to create an invisible stub of the object in the DOM and then clone it n-times, each time editing proprieties (eg like book's title and thumb).
Which is the best practice?
Performance are not the main focus. Code manutenibility and simplicity is my focus. I already use jQuery.
Avoid "clones" and use a client-side templating solution like Mustache or Handlebars . Load your templates (preloaded in variables, via AJAX, whatever), cache them (in objects, arrays, variables, whatever) for reuse then build them via jQuery:
//the data
var data = {
text : 'foo'
}
//HTML template string
var templateString = '<div><span>{{text}}</span></div>';
//render contents to template
var templateWithData = Mustache.render(templateString,data);
//build using jQuery
//should now be a div that has a span that contains foo
var newElement = $(templateWithData);
You may want to use a templating engine. My personal favorite is icanhaz.js but there are a lot of other solutions available.
You´re better of with a Databinding Framework/Engine instead of template engines.
Databinding frameworks like knockoutjs
//View (Template)
<form data-bind="submit: addItem">
New item:
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p>Your items:</p>
<select multiple="multiple" width="50" data-bind="options: items"> </select>
</form>
// ViewModel - Here's my data model
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};
ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.