簡體   English   中英

如何將JS Object Literal與jQuery結合起來?

[英]How can I combine JS Object Literal with jQuery?

我正在清理我的JS代碼,並希望創建名稱空間並使用JS OO。 我發現了Rebecca Murphey關於Object Literal模式的神教程

現在我想知道我如何通過編寫如何使用它來實現例如jQuery UI自動完成:

// Pseudocode
$('#input_field').myNameSpace.my_search();

var myNameSpace= {
  my_search : function() {
    $(this).autocomplete({...});
  },

  my_other_function: function() {}
};

目前我正在使用自己的插件:

$('#input_field').my_search();


(function ($) {
  $.fn.my_search = function () {

    $(this).autocomplete({
      minLength: 2,
      source: function( request, response ) {
        jQuery.ajax({
          url: callback_url,
          dataType: "json",
          data: {
            term: request.term
          },
          success: function( data ) {
            response( jQuery.map( data, function( item ) {
              return {
                id: item.id,
                value: item.name,
                name_encoded: item.name_encoded
              }
            }));
          }
        });
      },
      select: function( event, ui ) {
        (...)
      }
    });
  }
})(jQuery);

任何幫助贊賞。

更新
我的第一個例子非常接近,James Kyburz也非常接近(但工作)。 我簡化了James的答案,以避免復雜的返回數據。

(function () {
  // Namspace which also kind of works like an interface
  $.fn.my_name_space = function(opt) {
    this.autosuggest_brand = autosuggest.autosuggest_brand;
    return this;
  }

  var autosuggest = {
    autosuggest_brand : function(action) {
      $(this).autocomplete({
        // Autocomplete stuff here
      });
    },
    som_other_function _ function() {}
  }
})(jQuery);

不,你不能為jQuery插件使用命名空間(或者只是非常復雜 - 當你在命名空間對象上執行.my_search()方法時,選擇的上下文會丟失)。

你當前的插件很好; 如果你想要命名空間,那么使用像namespace_search這樣的前綴。

我還在努力,但不認為這是可能的

一種方法是將一切都包裝在函數中,而不是命名空間......

$.fn.my_namespace = function() {
  var el = this;
  var foo = function() { console.log('foo', el); };
  var bar = function() { console.log('bar', el); };
  return { foo: foo, bar: bar };
}

$('input:first').my_namespace().foo() // foo, [input...]
$('input:first').my_namespace().bar() // bar, [input...]

除非您需要使用defineProperty支持舊瀏覽器,否則可能是一種解決方案

Object.defineProperty($.fn, 'my_namespace', {
  get: function() {
    var el = this;
    return {
      foo: function() { console.log( 'foo', el); },
      bar: function() { console.log( 'bar', el); },
    }
  }
});

$('input:first').my_namespace.foo() // foo, [input...]
$('input:first').my_namespace.bar() // bar, [input...]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM