EDIT: Heres the example: https://github.com/prakash-anubavam/alloypreloadedsqlitedb/tree/master/app
And sumarizing, how does the view details.xml know which model is it taking the data from?
Coming from asp.net mvc, im having some issues understanding this MVC.
I can understand how to use tables and such on the view like:
<TableView id="table" dataCollection="fighters" onClick="showId" dataTransform="transformData">
And fetch the data in the controller, i know it will use the global (singleton) collection of fighters and that will bind the model to the view.
But i have come across an example (i cant really find now) where it had a View, with no table, just some labels and text='{variableName}', which i assume it gets from the model.
However the controller, did not assign the model (coming from an args[0] because it was always called from another controller which had the actual table), but it never assigned the model instance to the view in any way... so the question is how did it work? Is alloy smart enough to detect the actual model instance and use it? How would i do it? Something like $model = ...; or $.details.model = ...; or something like that? How did the view know where to take '{variableName}' from if the model was never assigned with a table or something.
This is actually a carryover hack, that may not work in the future, according to this thread.
If you take a look at index.js in your example (the controller), the model is assigned by the onClick event of the TableView:
function showId(e) {
if (e.row.model) {
var detailObj=fighters.get(e.row.model);
// Assigning to the $model actually sets this model as the one to bind too
var win=Alloy.createController('detail',{"$model":detailObj});
win.getView().open();
}
}
This is a "specai" variable that is automagically assigned for databinding, and is how it works underneath the covers (or did work under the covers).
This is undocumented and NOT ideal or recommended.
I've found Tony Lukasavage answer the cleaner aproach to bind a existing model to view:
You can find it here Josiah Hester answer is based on it (yeah, beware it's kind of a hack).
Although, Fokke Zandbergen gave an alternative worth looking at, maybe less hackish, don't know.
Expanding Josiah answer, you could do as follows:
On Master view:
<Alloy>
<Collection src="modelName" />
<View id="topview" class="container">
<TableView id="tblModels" dataCollection="modelName" dataTransform="transformModel">
<Require src="rowModel"/>
</TableView>
</View>
</Alloy>
Then, on master controller:
//retrieve the id of the model
var thisId = e.row.thisIndex;
//pass special key $model
var detailController = Alloy.createController("detail", { "$model": Alloy.Collections.detail.get(thisId) });
detailController.getView().open();
Then, on detail view:
<Alloy>
<View class="container" >
<Label text="{id}"/>
<Label text="{fullName}"/>
</View>
</Alloy>
On detail controller: do nothing special.
If you have a transform function on master controller, it returns a object and you can use its properties inside detail view like "{fullName}".
Related
Im struggling to delete a view's instance. On view hbs i use each loop to show view hbs. On another field click i add a " . " to a json object, which then adds another field to the template.
>js>App.ApplicationView = Ember.View.extend({
anotherField: [{name: 'testname'}],
actions: {
moreFields: function(){
this.get('anotherField').pushObject({name: ''});
},
less: function(){
var counter = this.get('anotherField');
counter.shift();
this.set('anotherField', counter);
And hbs
{{#each view.anotherField}}
{{view Ember.TextField}}
{{/each}}
<button {{action 'moreFields' target='view'}}> ++ </button>
<button {{action 'less' target='view'}}> -- </button>
http://jsbin.com/iSUdiCaX/17/edit
Cheers
Kristjan
When you use the shift method Ember doesn't get notified that the anotherField property changed, and therefore it doesn't update the template. You can check this by adding this.rerender() at the end of the less action.
You could:
call this.propertyDidChange('anotherField') to notify the property changed: http://emberjs.com/api/classes/Ember.Object.html#method_propertyDidChange
use the slice method: http://emberjs.com/api/classes/Ember.Array.html#method_slice
var sliced = this.get('anotherField').slice(0, this.get('anotherField').length - 1);
this.set('anotherField' sliced);
I also noticed you're using the View to handle the actions whereas I believe the Controller would be a better place to do so.
EDIT
Well it depends.... I believe the controllers are a good place because they have knowledge of the model (the view also has it via the controller). if your anotherField property is only needed for displaying or event handling logic then I believe it is a good idea to leave it in the view. from docs
Views in Ember.js are typically only created for the following
reasons:
When you need sophisticated handling of user events
When you want to create a re-usable component
But if instead the anotherField property is used the held application state (user selections, needed for computed properties or other actions) then I believe it's better placed inside the controller (and therefore the actions modifying it).
Have in mind your view can handle one part of the action and send it to the controller:
actions: {
something: function() {
.....
this.get('controller').send('something') // calls send action in controller
}
}
I hope this helps!
I'm trying using Backbone.Marionette to build an application. The application gets its data through REST calls.
In this application I created a model which contains the following fields:
id
name
language
type
I also created an ItemView that contains a complete form for the model. The template I'm using is this:
<form>
<input id="model-id" class="uneditable-input" name="id" type="text" value="{{id}}"/>
<input id="model-name" class="uneditable-input" name="name" type="text" value="{{name}}" />
<select id="model-language" name="language"></select>
<select id="model-type" name="type"></select>
<button class="btn btn-submit">Save</button>
</form>
(I'm using Twig.js for rendering the templates)
I am able to succesfully fetch a model's data and display the view.
What I want to do now is populate the select boxes for model-language and model-type with options. Language and type fields are to be restricted to values as a result from REST calls as well, i.e. I have a list of languages and a list of types provided to me through REST.
I'm contemplating on having two collections, one for language and one for type, create a view for each (i.e. viewLanguageSelectOptions and viewTypeSelectOptions), which renders the options in the form of the template I specified above. What I am not sure of is if this is possible, or where to do the populating of options and how to set the selected option based on data from the model. It's not clear to me, even by looking at examples and docs available, which Marionette view type this may best be realized with. Maybe I'm looking in the wrong direction.
In other words, I'm stuck right now and I'm wondering of any of you fellow Backbone Marionette users have suggestions or solutions. Hope you can help!
Create a view for a Select in my opinion is not needed in the scenario that you are describing, as Im assuming that your languages list will not be changing often, and the only porpouse is to provide a list from where to pick a value so you can populate your selects in the onRender or initializace function of your view using jquery.
you can make the calls to your REST service and get the lists before rendering your view and pass this list to the view as options and populate your selects on the onRender function
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function (options) {
this.languages = options.languages;
this.typeList = options.typeList;
},
template : "#atemplate",
onRender : function () {
this.renderSelect(this.languages, "#languagesSelect", "valueofThelist");
this.renderSelect(this.typeList, "#typesSelect", "valueofThelist")
},
renderSelect :function (list, element, value) {
$.each(list, function(){
_this.$el.find(element).append("<option value='"+this[value]+"'>"+this[value]+"</option>");
});
}
})
var languagesList = getLanguages();
var typeList = getTypesList();
var myItemView = new MyItemView({languages:languagesList,typeList :typeList });
Hope this helps.
I'm looking for some clarification on views in Ember.js
Coming from a rails background and I'm trying to ignore any preconceptions. From what I understand of the ember framework there are 5 components:
Routes: This is where we define the state of the application. The state is reflected in the URL. We can also define data loading here. Route classes are defined and on startup ember creates route objects which last for the duration of the application.
Models: This is where object data is defined. Can also define computed properties. A model object is created for each json object returned from the server.
Controllers: This mediates interactions between the models and templates/views. Controller classes are defined and on startup ember creates controller objects which last for the duration of the application. There is only ever a single instance of each controller class.
Templates: These describe the generated markup.
Views: These are specific templates or dom elements relating to a model. These are used to define interface events and send them to the controller for handling. Not sure when to create these.
As an example lets say I have a EventsController that has data loaded on the applicationRoute:
ScheduleApp.EventsController = Ember.ArrayController.extend();
ScheduleApp.ApplicationRoute = Ember.Route.extend({
setupController: function() {
this.controllerFor('events').set('content', ScheduleApp.Event.find());
}
});
Now in my template instead of iterating over each and displaying the information I want to iterate over each and create an associated view so I can add interactions to each event. I presume I would need to create a new view for each event and have it display in my template. However, I'm not sure where I create these views. Do I define a view class and then ember will create a new view object each time I call it using the view helper? Eventually I would like to use the appendTo on the view to inject my events to different places in the dom. Where would this be defined?
I've tried reading over the ember.js guide for views but it describes the context of a creating a single view. I think I want to make many views for each event and then dynamically interact with those objects.
Up to now ember has been outrageously clever so I would assume there is a built in method for generating these views. After all, most user interfaces are full of lists that require interactions. The problem is the list I'm trying to make I then want to spread over the dom depending on its attributes.
As per your code, App.EventsController has a list of events, now let us say we want the UI to have a list of events displayed and for each event say we want the view to have a delete button which deletes the event when the user clicks
One way to accomplish is by using Ember.CollectionView, the collection view as the name suggests is tailored for these sort of requirements, in many Ember examples the usage of view is not defined because ember auto-generates it for you but in some cases we might need to explicitly define a view to meed our requirements
App.EventsView = Ember.CollectionView.extend({
// It needs a list of data to iterate upon
// We are binding it to the controllers content data which
// is a list of events
contentBinding: "controller.content",
appendSpan: function(){
view = Ember.View.create({tagName: 'span'});
this.get("childViews").forEach(function(child){
view.appendTo(child);
});
},
// Now we need to also define a view template that will be
// generated for all the elements in the content array
// This could in turn be another collection view if required
// I am going to keep it simple for now
itemViewClass: Ember.View.extend({
templateName: "event",
deleteEvent: function(){
// Implement Delete
this.get("content").deleteRecord();
},
notifyUser: function(){
// The record doesn't get deleted as soon as user clicks, the request goes to
// server and server deletes the record and sends back the response to the
// client, Hence I'm using an observer here on isDeleted property of the record
if(this.get('content.isDeleted')){
alert("Record deleted Successfully");
}
}.observes('content.isDeleted')
})
})
Important Note Inside the CollectionView definition this.get("content") refers to the array of events, while in itemViewClass this.get("content") refers to the single event object
//Defining the template
//Assuming the event model has a name property
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
</script>
Now when you hit your application_url/events
you'll a list of events each event has a delete button, I hope this clears some concepts
For more information about CollectionView
Update as per the comment:
If you want to append another view to each child view, you can do so by editing the template of itemViewClass as follows
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
{{ view App.SomeOtherView }}
</script>
it can be a partial too as follows
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
{{ partial "somePartial" }}
</script>
or if you want to do it programmatically say, you click a button in the EventsView template and on click all the childs view must have a span tag appended to it(I am very bad at giving examples)
//This is the template for App.EventsController,
//template-name = "events" => view is App.EventsView and controller App.EventsController
<script type="text/x-handlebars" data-template-name="events">
<a {{action appendSpan target="view"}} href="#"> Append </a>
</script>
appendSpan is defined in the CollectionView
Hello everyone I'm trying to do change text color in my controller. Yes I did it but I have to send two parameter to my view. So is there any alternative way to change color in controller method ?
Here is my controller:
public action Test ()
{
ViewBag.stackoverflow = "It's gonna be red";
ViewBag.color = "red";
}
And my view:
#{
ViewBag.Title = "Test me";
}
<font color="#ViewBag.color">#ViewBag.stackoverflow</font>
I was just trying to figure out this same thing. All I did was wrap my ViewBag in view with a bootstrap class:
<div class="text-danger">
#ViewBag.Message //Message comes out red
</div>
In ASP.NET MVC, Controller and View communicate via Model that you send to view. So there is no way.
But it is good thing. MVC introduces separation of various concerns. One of many advantages is testability.
One more thing. your "color"property on ViewBag is not good idea neither. Try to describe the purpose of highlighted value like "priority" or something else and later in view you can decide the color to use for different levels of priority.
I found using the tag with the class from bootstrap helped. Very easy:
<span class="alert-success">
#Html.Raw(TempData["Message"])
</span>
I'm moving my WebForms project to MVC and having a hard time designing things.
The basic display of my app is in _Layout. The page is divided into 4 parts(say Part A,B,C and D), with 3(A,B,C) just containing html and one(D) is dynamic. I had used #RenderBody to bring in the content of Part D. However, now the other parts are changing and I need separate controllers for these parts. What is the best way to get their contents to be displayed into _Layout?
#Html.RenderPartial / #Html.Partial / #Html.RenderAction / #Html.Action ?
I'm currently trying to replace Part C by using -
#Html.Action("Index", "CController")
However, this is not working.
In Index.cshtml for CController, I've the Layout = null, initially it was set to point to _Layout.cshtml, but I read here that this created issues.
After putting the C Part in CControllers view, it does not event display the basic _Layout page that it displayed earlier.
Here's the Index.cshtml of CController -
<div id="noteContainerDiv">
Here goes all the data to display
</div>
And Here's the code for CController.cs -
public class CController : Controller
{
public ActionResult Index()
{
return PartialView();
}
}
Can anyone suggest the right way to design this?
What you could do is have a view model for your subview (the one you call D) and pass in this view model from your layout view.
I.e. by doing something like this in your _Layout:
#Html.Partial("_SubviewD", Model.SubviewDModel)
Then obviously in your controllers you need to initialize this subview model and include it in your model (or alternatively, in the ViewBag--apologies for suggested being evil!) You could even find ways to do this without changing all your controllers (for example through a base Controller class and overriding OnActionExecuted).
There are many ways you could do this. But I would stick to your initial approach.
Have your CController Index action return a PartialViewResult instead of a full result.
You don't set the layout for partial views. So in your CController index action you'll have something like this:
var model = ....
return this.PartialView("NameOfYourPartialView", yourModel);
And when you call
#Html.Action("Index", "CController")
Everything should be OK, cool?