简体   繁体   English

原型到javascript

[英]prototype to javascript

What is the equivalent javascript code for this prototype code? 这个原型代码的等效javascript代码是什么?

var Confirm = Class.create();
Confirm.prototype = {
        initialize: function(element, message) {
                this.message = message;
                Event.observe($(element), 'click', this.doConfirm.bindAsEventListener(this));
        },

        doConfirm: function(e) {
                if(! confirm(this.message))
                        e.stop();
        }
}

Roughly speaking: 粗略地说:

var Confirm = (function()
    function Confirm(element, message) {
        var self = this;
        this.message = message;
        hookEvent(element, "click", function(event) {
            self.doConfirm(event);
        });
    }
    Confirm.prototype.doConfirm = Confirm$doConfirm;
    function Confirm$doConfirm(e) {
        if (!confirm(this.message)) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            else {
                e.cancelBubble = true;
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            else {
                e.returnValue = false;
            }
        }
    }

    return Confirm;
})();

(You can shorten that slightly if you don't mind using anonymous functions; I prefer to help my tools help me by giving functions names.) (如果你不介意使用匿名函数,你可以稍微缩短一下;我更喜欢通过给出函数名来帮助我的工具帮助我 。)

In the above, hookEvent is a utility function you'll have to provide that either calls addEventListener or attachEvent (to support IE8 and earlier) as appropriate, something like this: 在上面, hookEvent是一个实用程序函数,你必须提供调用addEventListenerattachEvent (以支持IE8及更早版本),如下所示:

function hookEvent(element, eventName, handler) {
    // Very quick-and-dirty, recommend using a proper library,
    // this is just for the purposes of the example.
    if (typeof element.addEventListener !== "undefined") {
        element.addEventListener(eventName, handler, false);
    }
    else if (typeof element.attachEvent !== "undefined") {
        element.attachEvent("on" + eventName, function(event) {
            return handler(event || window.event);
        });
    }
    else {
        throw "Browser not supported.";
    }
}

Note how much more work is required for cross-browser compatibility. 请注意跨浏览器兼容性需要做多少工作。 You don't have to use Prototype, but I do strongly recommend you use another decent library even if not Prototype, like jQuery , YUI , Closure , or any of several others . 您不必使用Prototype,但我强烈建议您使用另一个不错的库,即使不是Prototype,如jQueryYUIClosure其他任何一个 You'll save a lot of effort working around cross-browser differences and dealing with edge cases that come up by leveraging the significant work done by others in this area. 通过利用其他人在该领域所做的重要工作,您将节省大量精力解决跨浏览器差异并处理边缘案例。

If your goal is to move off Prototype rather than moving off libraries entirely, here's that same thing using jQuery for instance: 如果你的目标是离开Prototype而不是完全移出库,那么就像使用jQuery一样:

var Confirm = (function()
    function Confirm(element, message) {
        this.message = message;
        $(element).click($.proxy(this.doConfirm, this));
    }
    Confirm.prototype.doConfirm = Confirm$doConfirm;
    function Confirm$doConfirm(e) {
        if (!confirm(this.message)) {
            return false;
        }
    }

    return Confirm;
})();

That uses $().click for hookEvent , $.proxy to avoid creating an explicit closure (still creates one, just does it for you behind the scenes), and the fact that in jQuery event handlers, return false is the same as both stopping propagation and preventing the default action (just like Prototype's stop ). 这使用$().click for hookEvent$.proxy以避免创建一个显式的闭包(仍然创建一个,只是在幕后为你做),并且在jQuery事件处理程序中return false的事实与两者相同停止传播并阻止默认操作(就像Prototype的stop )。 You could also use stopPropagation and preventDefault without worrying about browser differences; 您也可以使用stopPropagationpreventDefault而不必担心浏览器差异; jQuery handles it for you. jQuery为你处理它。 Most libraries will. 大多数图书馆会。

If you move off Prototype but still want something akin to its Class feature, here's one you can drop into your code. 如果你动过原型,但仍希望一些类似于其Class的功能, 这里有一个你可以拖放到你的代码。 My goal in that blog post wasn't to replace Prototype's Class (at the time I was using Prototype), but rather to fix what I found was Prototype's hugely inefficient way of handling supercalls. 我在博客文章中的目标不是取代Prototype的Class (当时我正在使用Prototype),而是修复我发现的Prototype处理超级调用的非常低效的方式。 But in doing that, well, a full implementation that can replace Class got created. 但是,在这样做的过程中,创建了一个可以取代Class的完整实现。 I really need to update the terminology in it, because of course it's not about classes at all (JavaScript doesn't have classes), it's just about some handy plumbing sugar for JavaScript's prototypical inheritance. 我真的需要更新它中的术语,因为它当然不是关于类(JavaScript没有类),它只是JavaScript的原型继承的一些方便的管道糖。

(Inb4 Raynos arrives with his pd craziness.) (Inb4 Raynos带着他的pd疯狂到来。)

function Confirm(element, message) {
    this.message = message;

    element.addEventListener("click", this.doConfirm.bind(this), false);
}

Confirm.prototype.doConfirm = function (e) {
    if (!confirm(this.message)) {
        e.preventDefault();
        e.stopPropagation();
    }
};

Depends on how abstract you want it to be. 取决于你想要的抽象程度。 In the simplest case: 在最简单的情况下:

<button onclick="return confirm('Are you sure?')">something</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM