knockout将附加参数传递给订阅功能

时间:2013-11-26 11:46:21

标签: javascript jquery ajax knockout.js

我想要实现的是为模型属性创建订阅。此订阅函数应通过Ajax更新数据库中的属性值来调用WebApi。对于ajax调用,我需要三个参数:“fieldName”,“fieldValue”和“modelId”,ajax将根据这三个参数更新数据库行。

我有很多属性,所有属性都需要相同的功能,所以我不想单独订阅每个属性,所以我找到了以下建议:

ko.subscribable.fn.withUpdater = function (handler) {
    var self = this;    
    this.subscribe(handler);    
    //support chaining 
    return this;    
};

添加它是如何“附加”到observables:

self.ModelId= ko.observable();
self.CompanyName = ko.observable().withUpdater(update);

其中update是模型外的一些js函数。

然而,我有问题,因为我无法将三个参数传递给update函数(或者我可以说另一句话 - 我需要能够获得viewModel.ModelId属性值update,以及propertyName)。

function update (propertyName, propertyNewValue, anotherPropertyValue) {
  //do ajax update 
}

作为CompanyName属性的示例,它将是:

update("CompanyName", "New Company value here", 3), 

,其中

3 == viewModel.ModelId

2 个答案:

答案 0 :(得分:1)

可能有更好的方法可以做到这一点,但以下方法可行:

首先,将目标对象添加到withUpdate方法:

ko.subscribable.fn.withUpdater = function (handler, target, propname) {
    var self = this;   

    var _oldValue;
    this.subscribe(function (oldValue) {
      _oldValue = oldValue;
    }, null, 'beforeChange');

   this.subscribe(function (newValue) {
     handler.call(target, _oldValue, newValue, propname);
   });

       return this;     
};

更新订阅功能将限定为目标属性:

var update = function (propertyName) {
   console.log('propname is '+ propname + ' old val: ' + oldvalue + ', new val: ' +  newvalue + ', model id: ' + this.ModelId());
}

现在你需要稍微改变它。

  self.CompanyName = ko.observable().withUpdater(update, self, "CompanyName");

示例http://plnkr.co/edit/HhbKEm?p=preview

我无法将withUpdater函数的范围变为对象的范围,而无需显式传入目标和公司名称的字符串。

答案 1 :(得分:0)

您可以将函数声明为'fn'范围之外的变量。

var dataservice = 'my class that has the data calls';

var altFunc = function () {
        
    return ko.pureComputed(function () {
        var currentItem = this().filter(function (item) {
        
// Do knockout stuff here and return your data
// also make calls to the dataservice class
        
        }, this, dataservice);

        
    };


ko.observableArray.fn.someNewFunctionality = altFunc;
相关问题