开发者

Best way to link UI elements with backing javascript objects

This is a rephrase of a post I made last week. I was surprised I didn't get more of a response, thinking maybe I didn't describe/title it very well.

Simplest possible way to describe it:

Is there something like spring:bind for javascript/dhtml?

The high level view of what I want:

In my app, I have a list of "subscriber" objects which I've loaded via ajax. I'd like to dynamically draw UI elements representing these objects, and register event handl开发者_StackOverflow中文版ers so that the backing objects are updated when the user edits the view.

The more low level thoughts

Dynamically displaying js data in the browser is trivial. It's also not a big problem to write event handlers for every type of data, but it's a bit tedious. I feel like there should be some library out there which will behave as a template system, creating HTML form elements dynamically, populating placeholders with data from my js objects, but go to the additional step of updating the backing objects when the user makes edits to the form elements. The closest example I'm aware of is a back-end technology, the Spring (java framework) binding functionality, where form elements in templates are coded according to a system where they're automatically linked to the model objects on the server.

So, does what I've described exist in the front-end world?


I do not know about libraries of the kind you described, but jQuery offers the very useful data() function which allows you to associate an arbitrary piece of data with a DOM element, using a key. Adding a new element and associating data with it might look like this:

var elem = $('<div class="subscriber">...</div>').appendTo(someContainer);
elem.data('yourKey', backingObject);

Using event delegation (e.g., the live() function), you can add one event handler that is valid for all graphical representations of your subscriber objects, no matter if they already exist or not.

$('.subscriber').live('click', function(e) {
    var backingObject = $(this).data('yourKey');
    // Now call some methods on the backing object
});

Hope this helps you somehow.


This is not an answer, but a larger comment. It might help to write the API you want to use, such as:

var jsObj = {};

jsObj.bind(document.getElementById("firstName"), "onchange");
//binds the data from the firstName element to the jsObject in property "firstName" during the onchange event.

Is this what you are trying to do?

A quick google search turns up: http://api.jquery.com/bind/

It might be interesting to make a delegate to jQuery's bind, which doesn't see to hard to do.


Knockout looks like it does the job you are looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜