I'm new to ember I am trying to append a template to another and it seems to work but it raises an error, can you please explain why?
The error:
Assertion failed: You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead
This is the code in app.js
App.NewStickie = Ember.View.extend({
click: function(evt){
var stickie = Ember.View.create({
templateName: 'stickie',
content: 'write your notes here'
});
stickie.appendTo('#stickies');
}
});
These are the contents of index.html
<script type="text/x-handlebars">
{{#view App.NewStickie}}
<button type="button" class="btn btn-success">
New
</button>
{{/view}}
{{outlet}}
</script>
<script type="text/x-handlebars" id="index">
<div id="stickies">
{{#each item in model}}
<div class="stickie" contenteditable="true">
{{#view App.DeleteStickie}}
<span class="glyphicon glyphicon-trash"></span>
{{/view}}
<div contenteditable="true">
{{item.content}}
</div>
</div>
{{/each}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="stickie">
<div class="stickie">
{{#view App.DeleteStickie}}
<span class="glyphicon glyphicon-trash"></span>
{{/view}}
<div contenteditable="true">
{{view.content}}
</div>
</div>
</script>
Each view in ember have a template, for example:
foo_view.js
App.FooView = Ember.View.extend({
templateName: 'foo'
})
foo template
<script type="text/x-handlebars" data-template-name="index">
<div id=myFooView>Foo</div>
</script>
You are trying to insert a view inside of other in that way:
App.BarView.create().appendTo('#myFooView')
This isn't allowed. You can use the {{view}} handlebars helper to render a view inside other like that:
foo template
<script type="text/x-handlebars" data-template-name="index">
<div id=myFooView>
Foo
{{view App.BarView}}
</div>
</script>
But I think that you want this working dynamically. So you can use the ContainerView, like described by the error message:
App.StickiesView = Ember.ContainerView.extend({
click: function() {
var stickie = Ember.View.create({
templateName: 'stickie',
content: 'write your notes here'
});
this.pushObject(stickie);
}
})
I see in your code a lot of views with the click event, ember encourage you to use actions, this give more flexibility, error/loading handling etc. I think is a good idea to use it.
I hope it helps
You should probably read this guide that explains that ContainerView is. Also, I don't think it's necessary to create another View to append a template to another template.
Related
I am trying to call some code after an Ember {{#each}} tag has finished looping through its items. I have seen other questions that looked similar and the answer always implemented didInsertElement on the view. This does not seem to work for me as I am trying to access html objects that are not rendered with the view because they are in the {{#each}}.
Here is what my html looks like.
<script type="text/x-handlebars" id="user">
{{#if isEditing}}
<div class="well">
{{partial 'user/edit'}}
<button {{action 'doneEditing'}} class="btn btn-default">Save</button>
<button {{action 'cancelEditing'}} class="btn btn-default">Cancel</button>
</div>
{{else}}
<button {{action 'edit'}} class="btn btn-default">Edit</button>
{{/if}}
</script>
<script type="text/x-handlebars" id="user/edit">
{{#view 'editor'}}
<div id="sList" class="btn-group-vertical" role="group">
{{#each s in model}}
<button class="btn btn-default">
{{s.theme}}
</button>
{{/each}}
</div>
{{/view}}
</script>
And my javascript
App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.all('strength')
}
});
App.UserController = Ember.ObjectController.extend({
isEditing: false,
actions: {
edit: function(){
this.set("isEditing", true);
},
doneEditing: function(){
this.set("isEditing", false);
},
cancelEditing: function(){
this.set("isEditing", false);
}
}
});
App.EditorView = Ember.View.extend({
didInsertElement: function() {
//Do something to the button elements
}
});
When I try to run this, as soon as I hit the edit button and the partial loads, I get an error in the console after didInsertElement tried to access the button elements. It as if the elements in the div have not rendered yet. So how can I tell if the {{#each}} is done inserting elements into the html? I know this may be confusing but any and all help is appreciated.
Schedule your code in the afterRender queue to run after the contents of the view has been rendered.
App.EditorView = Ember.View.extend({
didInsertElement: function() {
Ember.run.schedule('afterRender', function() {
this.$().find('button').each(function() {
// $(this) is a button in this function
});
}.bind(this));
}
});
index.html:
<div id="section_a">
<script type="text/x-handlebars" data-template-name="index">
First value: {{input type="text" value=one}}<br>
Second value: {{input type="text" value=two}}<br>
Result: {{result}}
</script>
</div>
<div id="section_b">
<!-- Display {{result}} here aswell -->
</div>
application.js
App.IndexController = Ember.ObjectController.extend({
one: 0,
two: 0,
result: function() {
return this.get('one') + this.get('two');
}.property('one', 'two')
});
I have a section of a page where I have some Ember interactions - a user inputs some values and a calculated result is displayed.
I now want to have the calculated result displayed in another part of the page that is outside the defined template, how would I accomplish this?
You could bind that property to the application controller and then use it anywhere you want in the application. For example:
App.ApplicationController = Ember.ObjectController.extend({
needs: ['index'],
indexResult: Ember.computed.alias('controllers.index.result')
});
Now you can use it anywhere within the application you want. Just tell the outlet's controller to need the application controller, then call that property in the template. Like so:
App.FooController = Ember.ArrayController.extend({
needs: ['application'],
//...
});
In the Foo template:
{{controllers.application.indexResult}}
Or, if you are within the application scope you can just do:
{{indexResult}}
One simple and straight forward solution would be:
<script type="text/x-handlebars" data-template-name="index">
<div id="section_a">
First value: {{input type="text" value=one}}<br>
Second value: {{input type="text" value=two}}<br>
Result: {{result}}
</div>
<div id="section_b">
<!-- Display {{result}} here aswell -->
</div>
</script>
You can also set up another outlet that can be used to display the "result". You can read more about using outlets in the Ember.js Guides at http://emberjs.com/guides/routing/rendering-a-template/
So, Basically i'm new to meteor(0.8.2) and trying to create a basic app having two templates(addnewPlace and Map) and a single button. What i need to get is that, when i click on "Add new Place" button, template "addNewPlace" should be loaded in body or else template "Map" should be loaded. Help will be appreciated :)
My html code:
<body>
{{> menu}}
{{> body}}
</body>
<template name="body">
{{#if isTrue}}
{{> addnewPlace}}// tested this template individually, it works.
{{else}}
{{> maps}} // tested this template individually, it works too.
{{/if}}
</template>
<template name="menu">
<h1>Bank Innovation Map</h1>
<input type="button" value="Add new Place">
</template>
My js code:
Template.body.isTrue = true;
Template.menu.events({
'click input': function(){
//load a new template
console.log("You pressed the addNewplace button");//this fn is called properly
Template.body.isTrue = true;
}
});
Well first of all you obviously aren't changing anything in the click event (true before, true after). But also if you did, I think you might be better off using a session variable for this, to maintain reactivity.
Session.setDefault('showAddNewPlace', false)
Template.body.isTrue = function() { Session.get('showAddNewPlace'); }
Template.menu.events({
'click input': function(){
//load a new template
console.log("You pressed the addNewplace button");//this fn is called properly
Session.set('showAddNewPlace', true)
}
});
Meteor 0.8.2 comes in with the dynamic template include feature. Just set a session variable value on click event and you would like to use the template name on the event.
Session.setDefault('myTemplate', 'DefaultTemplateName');
"click input": function (event) {
Session.set("myTemplate", 'template_name');
}
You can now write this:
<body>
{{> menu}}
{{> body}}
</body>
<template name="body">
{{> UI.dynamic template=myTemplate}}
</template>
<template name="menu">
<h1>Bank Innovation Map</h1>
<input type="button" value="Add new Place">
</template>
You may like to take a look at this article for the reference:
https://www.discovermeteor.com/blog/blaze-dynamic-template-includes/
Does anyone happen to know How to show data from server, right now ive been showing related models in basic handlebars like this
{{
view Ember.Select
prompt="Organization"
contentBinding="organizations"
optionValuePath="content.id"
optionLabelPath="content.name"
selectionBinding="selectedOrganization"
}}
But i need to create an has many form... which im duplicating using views? Is using views even the right path to go ?!
{{#each view.anotherField}}
{{view Ember.TextField value=view.name}}
{{/each}}
Here is the output of my form, u can see Organizatons form being doubled
JSbin http://jsbin.com/efeReDer/7/edit
Today I came up with this... :D Kinda serves the purpose ? looks ugly tho
http://emberjs.jsbin.com/acUCocu/6/edit
Basically i made an empty model which i then each loop.
On action i "store.create".empty record to it.
Give me your thoughts on this :)
Also is there a way to make these fields indepedent ? without all changing their content while an input is changed.
Cheers,
kristjan
Here you can find an example to work on, of what i think you are asking
http://emberjs.jsbin.com/iPeHuNA/1/edit
js
Tried to separate the entities related to the model of the app, from how they will be displayed.Created an ember class App.Person that will hold the data from server. I have not used ember-data, but it is quite easy to replace the classes with ember-data notation and the dummy ajax calls with respective store calls etc, if desired.
App = Ember.Application.create();
App.Router.map(function() {
this.route("persons");
});
App.IndexRoute = Ember.Route.extend({
beforeModel: function() {
this.transitionTo("persons");
}
});
App.PersonsRoute = Ember.Route.extend({
model:function(){
return $.ajax({url:"/"}).then(function(){/*in url it is required to place the actual server address that will return data e.g. from a rest web service*/
/*let's imagine that the following data has been returned from the server*/
/*i.e. two Person entities have already been stored to the server and now are retrieved to display*/
var personsData = [];
var person1 = App.Person.create({id:1,fname:"Person1",lname:"First",genderId:2});
var person2 = App.Person.create({id:2,fname:"Person2",lname:"Second",genderId:1});
personsData.pushObject(person1);
personsData.pushObject(person2);
return personsData;
});
},
setupController:function(controller,model){
/*this could also be retrieved from server*/
/*let's mimic a call*/
$.ajax({url:"/",success:function(){
/*This will run async but ember's binding will preper everything.If this is not acceptable, then initialization of lists' values/dictionary values can take place in any earlier phase of the app. */
var gendersData = [];
gendersData.pushObject(App.Gender.create({id:1,type:"male"}));
gendersData.pushObject(App.Gender.create({id:2,type:"female"}));
controller.set("genders",gendersData);
model.forEach(function(person){
person.set("gender",gendersData.findBy("id",person.get("genderId")));
});
}});
controller.set("model",model);
}
});
App.PersonsController = Ember.ArrayController.extend({
genders:[],
actions:{
addPerson:function(){
this.get("model").pushObject(App.Person.create({id:Date.now(),fname:"",lname:""}));
},
print:function(){
console.log(this.get("model"));
}
}
});
App.PersonFormView = Ember.View.extend({
templateName:"personForm",
/*layoutName:"simple-row"*/
layoutName:"collapsible-row"
});
App.Person = Ember.Object.extend({
id:null,
fname:"",
lname:"",
gender:null
});
App.Gender = Ember.Object.extend({
id:null,
type:null
});
html/hbs
created a view that takes care of how each App.Person instance gets rendered. As example partial and layouts have been used to accomodate bootstrap styling, as i noticed you used some in your example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ember Starter Kit</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/2.1.0/normalize.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
</head>
<body>
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="persons">
{{#each person in this}}
{{view App.PersonFormView}}
{{/each}}
<br/><br/>
{{partial "buttons"}}
</script>
<script type="text/x-handlebars" data-template-name="_buttons">
<button type="button" class="btn btn-primary" {{action "addPerson"}}>
add
</button>
<button type="button" class="btn btn-primary" {{action "print"}}>
print results to console
</button>
</script>
<script type="text/x-handlebars" data-template-name="personForm">
<div class="row">
<div class="col-md-6 col-xs-5">
<div class="form-group">
<label>First Name</label>
{{input class="form-control" placeholder="First Name" value=person.fname}}
</div>
</div>
<div class="col-md-6 col-xs-5">
<div class="form-group">
<label>Last Name</label>
{{input class="form-control" placeholder="Last Name" value=person.lname}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-2 col-xs-4">
{{
view Ember.Select
prompt="Gender"
content=controller.genders
optionValuePath="content.id"
optionLabelPath="content.type"
selectionBinding=person.gender
class="form-control"
}}
</div>
</div>
<!--</div>-->
</script>
<script type="text/x-handlebars" data-template-name="simple-row">
<div class="row">
{{yield}}
</div>
<br/><br/>
</script>
<script type="text/x-handlebars" data-template-name="collapsible-row">
<div class="panel-group" >
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href=#{{unbound person.id}}>
person:{{person.fname}}
</a>
</h4>
</div>
<div id={{unbound person.id}} class="panel-collapse collapse">
<div class="panel-body">
{{yield}}
</div>
</div>
</div>
</div>
</br>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.1.2.js"></script>
<script src="http://builds.emberjs.com/tags/v1.2.0/ember.min.js"></script>
</body>
</html>
I want a View to be hidden on load, then when a user clicks on a link it will display the view. Can someone review my code and let me know what I have done wrong?
App.parentView = Em.View.extend({
click: function() {
App.childView.set('isVisible', true);
}
});
App.childView = Em.View.extend({
isVisible: false
});
Here is the jsfiddle: http://jsfiddle.net/stevenng/uxyrw/5/
I would create a simple isVisibleBinding to the view you want to hide/show, see
http://jsfiddle.net/pangratz666/dTV6q/:
Handlebars:
<script type="text/x-handlebars" >
{{#view App.ParentView}}
<h1>Parent</h1>
<div>
<a href="#" {{action "toggle"}}>hide/show</a>
</div>
{{#view App.ChildView isVisibleBinding="isChildVisible" }}
{{view Em.TextArea rows="2" cols="20"}}
{{/view}}
{{/view}}
</script>
JavaScript:
App.ParentView = Em.View.extend({
isChildVisible: true,
toggle: function(){
this.toggleProperty('isChildVisible');
}
});
App.ChildView = Ember.View.extend();
A note about your naming conventions: classes should be named UpperCase and instances lowerCase. See blog post about this.
Valuebinding for some reasons didnt work for me so observing parentView property inside childView did the trick for me
Handlebar:
<script type="text/x-handlebars" >
{{#view App.ParentView}}
<h1>Parent</h1>
<div>
<a href="#" {{action "toggle"}}>hide/show</a>
</div>
{{#view App.ChildView }}
{{view Em.TextArea rows="2" cols="20"}}
{{/view}}
{{/view}}
</script>
Coffeescript:
App.ParentView = Em.View.extend
isChildVisible: true
toggle: ->
#toggleProperty 'isChildVisible'
App.ChildView = Em.View.extend
isVisible: (->
#get('parentView.isChildVisible')
).property '_parentView.isChildVisible'