commadelimited
commadelimited

Reputation: 5119

Writing and submitting a form view with Ember.js

I'm working on a proof of concept demo and I need to write a form view which will let me add items to my content array. I'm loading this view externally then compiling it using Handlers. I've added a submit method and used the {{action}} binding but each time I click the submit button it reloads the page. What am I missing?

// the template

<form>
    <div>
        <label for="client">Client Name</label>
        <input type="text" id="client" placeholder="Add client name" />
    </div>
    <div>
        <button {{action "addClientSubmit" target="PM.addClientView"}}>Add Client</button>
    </div>
    <div>
        <a href="#" {{action "closeWindow" target="PM"}}>close</a>
    </div>
</form>

// the view code

PM.addClientView = Ember.View.create({
    templateName: 'addClient',
    classNames: 'overlay',
    addClientSubmit: function(e){
        e.preventDefault();
        console.log('submitting add client form');
        console.log(a,b,c)
    }
});

// and finally here's how I'm adding it to the page

PM = Ember.Application.create({
    loadView: function(view){
        $.ajax({
            url: viewPath,
            success: function (template) {
                if (!Ember.TEMPLATES[templateName]) {
                    Ember.TEMPLATES[templateName] = Ember.Handlebars.compile(template);
                };
                PM[view + 'View'].appendTo('body');
            }
        });
    }
});

Everything else works, but when I click the submit button the page reloads. I'm sure I'm leaving something out but I can't figure out what it is.

Upvotes: 4

Views: 7846

Answers (2)

Jason P
Jason P

Reputation: 1415

The problem is that the template doesn't exist when the PM.addClientView is created.

Try changing PM.addClientView = Ember.View.create({ to PM.addClientView = Ember.View.extend({

and your success function to

PM[view + 'View'].create({ template: Ember.Handlebars.compile(template) }).append();

Here's a fiddle: http://jsfiddle.net/7E5zt/

Upvotes: 1

ebryn
ebryn

Reputation: 4407

You probably need to add type="button" to your button tag. The default is type="submit" which will trigger a form submission.

Here's a jsFiddle: http://jsfiddle.net/b2CTg/2/

Upvotes: 6

Related Questions