开发者

JQuery Widget - Pass options by reference

I have two JQuery widgets, one is a sort of 'main' widget, the other could be considered a child. The child handles gathering specific data which is required by the main. The main is used with AJAX requests. So, the main has a set of options which are sent to the server. One of these options is also an option in the child.

To make this more clear, I have a main widget which has a few options. It then creates and appends a child widget. This child widget has an additional option that is required to be filled in the main widget before an AJAX request may be sent. In order to make this work, I am passing to the child: this.options.someArray

This works fine, however when changes are made to that array in the child widget, they never reach back to the main widget. This means the AJAX request sends an empty array in this place. How can I fix this?

[If this is not standard behavior - I can post a code sample]

Code sample for main Widget:

$.widget('be.deckEditor', {
  options: {
    deck: { name: "", id: 0, cards: [],  tags: [] }
  },

Code to create child Widget:

tagEditBox = $('<div>');
tagEditBox.tagEditor({tags:this.options.deck.tags});

Widget _Init code:

_init: function () {
  开发者_StackOverflow社区this.options.tags = ['ace','two'];
},


If you want that "_init" code to re-set the "tags" contents, then don't set it to refer to a brand new array:

_init: function () {
  this.options.tags[0] = 'ace';
  this.options.tags[1] = 'two';
  this.options.tags.length = 2;
},

You could write a function to make a target array contain what another array contains; I don't think there's one built in but I can't recall ever wanting to find such a thing:

function arrayCopy(src, dest) {
  for (var i = 0; i < src.length; ++i) dest[i] = src[i];
  dest.length = src.length;
}

(The last line is only necessary if you want the destination to be a complete copy, length and all.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜