覆盖Knockout View-Model功能

时间:2016-05-18 11:04:03

标签: backbone.js knockout.js override extend

我在我的应用程序中使用knockout和backbone。我的test-view.js看起来像这样:

define([
  "knockout",
  "./base",
  "./../viewmodels/test-vm",
  "text!./../templates/test-template.html"
],

function(ko, BaseView, TestViewModel, template) {

  var TestView = BaseView.extend({
    template: template,

    initialize: function() {
      this.viewModel = new TestViewModel();
    },

    render: function(){
      this.$el.html(template);
      return this;
    },

    postRender: function() {
      ko.applyBindings(this.viewModel, this.el);
    }
  });

  return TestView;
});

测试template.html:

<button class="btn"  data-bind="click: test">test</button>

和test-vm.js如下:

define([],
  function() {

    function TestViewModel() {
      var self = this;

      self.test = function () {
        alert("in test view model");
      };
    }

    return TestViewModel;
  });

当我点击按钮时,会调用self.test。我的问题是如何在另一个文件中扩展TestViewModel并覆盖测试函数来做一些特定的事情?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您没有理由不使用常用的“Object.create经典继承”方法,如下所述:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

// Define the base class
var TestViewModel = function () {
  this.sharedProperty = true;
};

TestViewModel.prototype.test = function() {
  log("testing TestViewModel");
};

// Define the extended class
var ExtendedTestViewModel = function() {
  TestViewModel.call(this);
};

// Copy the prototype and reset the constructor
ExtendedTestViewModel.prototype = Object.create(TestViewModel.prototype);
ExtendedTestViewModel.constructor = ExtendedTestViewModel;

// Override the inherited `test` function
ExtendedTestViewModel.prototype.test = function() {
  // To call the base method: 
  // (skip this if you want to completely override this function)
  TestViewModel.prototype.test.call(this);
  
  // Add functionality:
  log("testing ExtendedTestViewModel");
};

// Create an instance
var etvm = new ExtendedTestViewModel();

// This will log both the inherited message, as well as the extended message
etvm.test();

// ExtendedTestViewModel has all properties that are in TestViewModel
log(etvm.sharedProperty);

// utils
function log(msg) {
  var pre = document.createElement("pre");
  pre.appendChild(document.createTextNode(msg));
  document.body.appendChild(pre);
};