0

What is the equivalent javascript code for this prototype code?

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();
        }
}
2
  • 5
    Prototype is JavaScript. Commented Jan 5, 2012 at 15:16
  • @FelixKling. This one goes first place in my favorite bar. Commented Jan 5, 2012 at 15:19

3 Answers 3

2

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:

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. 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:

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). You could also use stopPropagation and preventDefault without worrying about browser differences; jQuery handles it for you. 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. 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. But in doing that, well, a full implementation that can replace Class got created. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

"JavaScript doesn't have classes, and never will" --- careful with that last part! Some parts of es-discuss are pushing for them hard, although from what I've seen I don't think they'll make it into ES Harmony.
@Domenic: I was basing that on Brendan Eich's statement to that effect in his harmony email -- but I misremembered the statement! (Packages, namespaces and early binding are out for good; could have sworn classes was on that list, but it clearly is not.) Thus removed that from the above. :-)
1

(Inb4 Raynos arrives with his pd craziness.)

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();
    }
};

3 Comments

Prototype's stop does both preventDefault and stopPropagation. And of course, something like a third of all web users (more than that in China) are using IE8 or lower, which don't have addEventListener and the associated preventDefault / stopPropagation.
@T.J.Crowder Thanks for the Prototype tip. He asked for JavaScript though, not backward-compatible JavaScript, so I'll avoid sullying myself with IE8 ickiness and leave that to the other answers...
#dominic: Your call, of course, but ignoring such a huge percentage of the current reality is a pretty big omission.
-1

Depends on how abstract you want it to be. In the simplest case:

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

5 Comments

@Downvoter: please read meta.stackexchange.com/a/21086 to understand why it's important to comment your downvotes.
I didn't downvote you but I think you missed a lot of code there. Class.create(); does a lot more than your example.
And then there's the whole mixing markup and code, recommending someone move back to DOM0 from nice decoupled DOM2 code.
@T.J. Crowder: If OP wants "modern" unobtrusive javascript, they should use a framework. Pure javascript without a framework hardly makes sense nowadays - your own answer being a perfect illustration.
@thg435: I agree (as you could tell from my answer). But it doesn't necessarily follow that if they don't want to use Prototype, they don't want to use any framework and want to go back to 1997 event handlers. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.