如何构建knockoutJS Jquery应用程序

时间:2012-01-31 12:05:22

标签: jquery design-patterns structure knockout.js

**更新

我正在使用带有jquery的knockoutjs来构建一个应用程序。

因为我正在使用jquery,所以我必须在jquery函数中包含knockout。这很好,除了通过应用程序我重复使用相同的对象/功能用于各种不同的页面。因为该对象包含对knockout的引用,所以我不能将它们放在一个全局文件中,这意味着我有很多重复,严重膨胀我的代码并使其无法管理。

所以

//global file

//this is fine because it dose not reference knockout 
var global_cust = function(){
   this.name: "dave";
   this.isAwkward: true; 
}

//this is not fine because it references knockout 
var knockout_global_customer = function(properties){
  this.name: ko.observable(properties.name? properties.name: "unknown"),
  this.isAwkward: ko.observable(properties.isAwkward? properties.isAwkward: true),   
}

//page 1 

(function($){

//i have to include the customer in every page of aplplication that uses it. I would like this in a global file or someway of Precompiling it so don't have to include it in every page - a bit like php include but for JS    
var customer = function(properties){
  this.name: ko.observable(properties.name? properties.name: "unknown"),
  this.isAwkward: ko.observable(properties.isAwkward? properties.isAwkward: true),   
}

var viewModel = {
  currentCustomer: ko.observable(new customer()),
  globalCustomer: ko.observable(new global_cust()),
}

ko.applyBindings(viewModel);

})(jQuery);

无论如何都是这样,或者是预先处理文件的工具,这样我就不必在每个页面上复制相同的对象/功能

由于

2 个答案:

答案 0 :(得分:1)

您可以使用 window 变量来实现此目的。

window.customerModel = viewModel;

它将在全球范围内提供。

答案 1 :(得分:0)

我喜欢窗口变量的答案,并认为它最适合你。但是对于类似“php include”的函数,请查看jQuery.getScript函数:http://api.jquery.com/jQuery.getScript/