2010-09-20 124 views
0

说我有一个Form对象,它有一个Tab对象数组。jquery扩展 - 对象数组

var Tab = function (options) { 
    return ($jQuery.extend(true, { 
     id: 'foo', 
     title: 'Foo' 
    }, options)); 
} 

var Form = function (options) { 
    return ($jQuery.extend(true, { 
     id: 'foo', 
     tabs: [new Tab()] 
    }, options)); 
} 

我可以用这个:

var myForm = new Form({tabs: [new Tab({id: 'bar'}), new Tab({title: 'Bar'}), new Tab({id: 'bar', title: 'Bar'})]}); 

要获取:

myForm.tabs[0] => {id: 'bar', title: 'foo'} 
myForm.tabs[1] => {id: 'foo', title: 'Bar'} 
myForm.tabs[2] => {id: 'bar', title: 'Bar'} 

但是,它可能以某种方式做到这一点:

var myForm = new Form({tabs: [{id: 'bar'}, {title: 'Bar'}, {id: 'bar', title: 'Bar'}]}); 

,并得到相同的结果?

回答

0

您可以循环选项卡并检查它们是否为Tab对象,例如, (未经测试):

var Form = function (options) { 
    if(options && options.tabs) { 
     var tabs = options.tabs; 
     for(var i = 0, l = tabs.length; i < l; ++i) { 
      if(!(tabs[i] instanceof Tab)) { 
       tabs[i] = new Tab(tabs[i]); 
      } 
     } 
    } 

    return ($jQuery.extend(true, { 
     id: 'foo', 
     tabs: [new Tab()] 
    }, options)); 
} 

参考:instanceof

+1

感谢。我希望有一个简单的方法可以做到这一点,而无需编写额外的代码来处理它。这将完成这项工作。再次感谢! – Brett 2010-09-20 06:12:06