2012-03-01 23 views
5

我一直在爲項目創建可重複使用的組件作爲項目的一段時間。我喜歡能夠抽象出邏輯,並根據具體情況注入所有上下文(選擇器,選項等)。使用KnockoutJS創建可重複使用的組件

現在,我開始使用KnockoutJS,並且寫了一個很好的小jQuery插件,它使用Knockout作爲其內部邏輯。它工作得很好,但我想知道是否有更好的方法來做到這一點? Knockout本身是否具有創建可重用組件的模式/約定,或者此模式是否可用?

這是一個例子,它應該足以讓你知道我在做什麼。

/*globals jQuery, knockout */ 
(function ($, ko) { 
    "use strict"; 
    $.fn.itemManager = function (options) { 
     // set up the plugin options 
     var opts = $.extend({}, $.fn.itemManager.defaultOptions, options), 
      $wrap = $(this), 
      templateUrl = '/path/to/template/dir/' + opts.templateName + '.html'; 

     // set up the KO viewmodel 
     function ItemManagerModel(items) { 
      var self = this; 

      self.items = ko.observableArray(items); 
      self.chosenItemId = ko.observable(); 
      self.chosenItemData = ko.observable(); 

      // generic method for navigating the Item hierarchy 
      self.find = function (array, id) { 
       /* ... */ 
      }; 

      /* bunch of other stuff... */ 

      self.goToItem(items[0]); 
     } 

     // this is where the whole thing starts... 
     $(opts.openTriggerSelector).click(function (e) { 
      e.preventDefault(); 

      // set the template html 
      $.get(templateUrl, function (data) { 
       $wrap.html(data); 
      }); 

      // initial load and binding of the data, in reality I have some more conditional stuff around this... 
      // there's probably a better way to do this, but I'll ask in a separate question :) 
      $.get(opts.getItemsServiceUrl, function (result) { 
       ko.applyBindings(new ItemManagerModel(result), document.getElementById($wrap.attr('id'))); 
       $wrap.data('bound', true); 
      }); 

      // opens the template, which now is bound to the data in a dialog 
      $wrap.dialog({ /* ... */ }); 

    // provide default plugin options 
    $.fn.itemManager.defaultOptions = { 
     getItemsServiceUrl: '/path/to/service', 
     openTriggerSelector: 'a', 
     templateName: 'Default' 
    }; 
} (jQuery, ko)); 

回答

2

我爲KO組件運行github項目。它使用的是較早版本的KO,並且由於重大改造,但您可能能夠獲得一些想法。我基本上都是通過將模型對象作爲配置和數據的自定義綁定來完成的。

我一直在尋找更好的方法來做到這一點。如果你想出一個更好的方法,讓我貼出來。

https://github.com/madcapnmckay/Knockout-UI

+0

非常酷。所以我想「KO是否有創建組件的模式/約定」的答案基本上沒有呢? – 2012-03-02 21:36:30

+0

沒有我所知道的。我想將功能轉移到自定義綁定中是一種模式。在這方面這是相當有限的,但嘿有人可能會提出這方面的變化。 Knockout Validation是一個可重用的組件,它提供了擴展器來完成大部分工作。 – madcapnmckay 2012-03-02 22:17:25

相關問題