如何让它像jquery?

时间:2012-04-05 13:11:37

标签: javascript underscore.js

我刚刚创建了一个像underscoer.js这样的小型js框架。方法调用由mc_.grep([1,2,3,4], function(val){ return val > 2; });执行。我怎样才能使它更像jQuery样式mc_(var).grep(func..).map(func..);?有任何想法吗?还有我如何让图书馆变得更好?

https://github.com/awesomegamer/mc_-js-library

3 个答案:

答案 0 :(得分:3)

如果你想在每次从函数返回时想要链接函数调用,你必须返回,你必须返回包含在框架核心的基本对象内的东西,以便你可以调用下一个返回对象的方法。

例如(这是非常基本的)jQuery

返回$('#someid')调用
this.length = 1;
    this[0] = elem;
}

this.context = document;
this.selector = selector;
return this;

答案 1 :(得分:2)

// Your function should return a wrapped object
function Wrap(list) {
    return Object.create(Wrap).constructor(list)
}

// set the list as an internal property
Wrap.constructor = function (list) {
    this._list = list
    return this
}

// map function works in one of two ways, if it has an internal _list property
// then it was called as Wrap(list).map(...)
// then call the map function on it with the arguments
// store the result as a new list as _list
// return this so you can chain
//
// If it's not then it was used as Wrap.map(list, ...)
// extract the arguments using [].slice(arguments, 1)
// then return the result of invoking it
Wrap.map = function (list) {
    if (this._list) {
        this._list = this._list.map.apply(this._list, arguments)
        return this
    } else {
        return list.map.apply(list, [].slice.call(arguments, 1))
    }
}

// Wrappers need an unwrap method
// Wrap(list).map(...).filter(...).reduce(...).get()
Wrap.get = function () { 
    return this._list
}

答案 2 :(得分:1)

维基百科上有一篇名为"Method chaining"的好文章。

过度简化的链接示例,也可以作为working jsfiddle(只需打开控制台, F12 查看结果)如下:

var a = {
    b: function () {
        console.log('b');
        // Make method chainable:
        return this;
    },
    c: function () {
        console.log('c');
        // Make method chainable:
        return this;
    }
};

// Now you can do:
a.b().c();​

我建议看看annotated source code of underscore.js,以避免感觉“哦,该死的,我花了很多时间重新发明轮子”

如何改善?我只知道一种方法:让它变得有用。