2012-03-01 10 views
5

私はずっと以前からプロジェクト用のjQueryプラグインとして再利用可能なコンポーネントを作成してきました。私はロジックを抽象化することができ、状況(セレクタ、オプションなど)のすべてをケースバイケースで注入するのが好きです。KnockoutJSで再利用可能なコンポーネントを作成する

今、私はKnockoutJSを使い始めていて、内部論理にKnockoutを使った素敵な小さなjQueryプラグインを書いています。それはかなりうまくいくが、もっと良い方法があるのだろうか? 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はパターンを持っている/コンポーネントを作成するための慣習は"答えは、基本的にはないと思いますか? –

+0

私が知っていることはありません。機能のカスタムバインディングへの移行はパターンだと思います。これに関してはかなり制限されていますが、誰かがこれにバリエーションを出す可能性があります。ノックアウト検証は、多くの作業を行うエクステンダーを提供する再利用可能なコンポーネントです。 – madcapnmckay

関連する問題