开发者

jQuery Data Link not Handling Select Lists

I have a simple address form leveraging the awesome new Data Link plugin. It's a simple create/edit scenario that executes an ajax call to populate the form i开发者_如何学编程f an ID is present, or a blank form if not.

dataComplete : function(data){
        $self.step1Data = data;
        $self.Templates.step1('#step1form', $self.step1Data);
        $('#step1form').link($self.step1Data);
    }

The above function is called in either case, to link the form to the step1Data object (I just pass an empty JavaScript object to it if I don't have anything to populate the form). The 'Templates' object you see above is a simple wrapper that uses the also awesome jQuery Templates plugin.

This works great when editing; .link() conforms perfectly to the form and all is fine and dandy. The problem comes when dealing with an empty form: every field except the State select list is linked. Here's the html for the select list:

<select class="state" id="State" name="State">
    <option value="UT">Utah</option>
</select>

The class and id naming conventions are identical to the other parts of the form, but Data Link doesn't seem to notice it on it's own. I could probably configure it to do so manually, but for cleanliness I'd prefer not to if I can get away with it. Any ideas why it doesn't link the select list?


Okay, figured it out. According to this very detailed article by Schalck, when binding an empty form to an object with Data Link, the documentation implies behavior that is not really accurate.

Essentially, Data Link only sets up the link and events to create the properties within the object; it doesn't actually fulfill a two-way sync between them until the change event is triggered. In other words, until the user actually types something into the form field.

This behavior is fine for most controls (and for possible performance reasons, it makes a lot of sense to wait for user input). The issue is that the current documentation implies otherwise. With that in mind, I simply triggered the change event for the select lists in the form after the call to .link() like so:

    dataComplete : function(data){
        $self.step1Data = data;
        $self.Templates.step1('#step1form', $self.step1Data);
        $('#step1form').link($self.step1Data);

        //trigger the select lists
        $('[name=State]').trigger('change');
        $('[name=Type]').trigger('change');
    }

You could also simply iterate the input fields in the form and trigger all of their change events, if necessary. Below is one way, I'm sure there are better methods (DOM traversal here is form -> ul -> li -> inputs).

    $('.stepForm').children().children('input').trigger('change')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜