【问题标题】:how to write a general javascript plugin如何编写一个通用的 javascript 插件
【发布时间】:2012-10-05 10:42:09
【问题描述】:

我有以下 javascript 代码

$(function(){
    // loading source image
   $('#panel').mousemove(function(e) { // binding mouse move event
       // some code
   });
   $('#panel').mousedown(function(e) { // binding mousedown event
       // some code
   });
   $('#panel').mouseup(function(e) { // binding mouseup event
       // some code
   });
});

function getResults() {
    // some code
}

以这种方式工作

<button onclick="getResults()">Crop</button>
<canvas id="panel" width="100" height="200"></canvas>

我想重新编写这个 js-plugin 以使其更通用。
我认为使用它的一个好方法是以下方式:

$('#panel').myLib({
    onSelect: getResults,
    onClick: getResults
});

任何想法我应该如何重写我的 js 代码来获得这个结果? 谢谢

【问题讨论】:

  • 我建议开始here

标签: javascript jquery jquery-plugins plugins


【解决方案1】:

使用fn 属性(实际上是prototype 的别名)添加插件:

$.fn.myLib = function(options){

  // bind events
  this.mousemove(function(e) { // binding mouse move event
    // some code
  });
  this.mousedown(function(e) { // binding mousedown event
    // some code
  });
  this.mouseup(function(e) { // binding mouseup event
    // some code
  });

  // add a button
  this.before($('<button>').text('Crop').click(options.onSelect));

  // return the object to make the function chainable
  return this;
};

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多