Need suggestions to handle view updates - ractivejs

In an application currently I am loading my views using routers like below
router('menu/:item', function (item) {
app.uiHandler.toggleMenuSelected('menu', item);
// The below method updates the view with selected menu item's model.
app.channel.publish('menu', item);
});
Currently each menu item shares same data object. But the master view is replaced with new html based on each menu selection.
I am thinking to have instance like below for each menu item
var ractive = new Ractive({
el: 'container', // el is same for all instances.
template: '<p> I am {{selection}}, after {{prevSelection}}!</p>',
data: { selection: 'Home', prevSelection: 'Profile' }
});
But here my doubt is as I will be invoking each instance to render the view into 'container' whenever hash is changed how to clear all the two way data bindings created when master view is replaced with new html. Please help me on this.
If I am handling in wrong way, what would be the best way to handle the same.
Note : My question might sound like stupid, but I am looking for clarification on this :)

how to clear all the two way data bindings created when master view is replaced with new html
You can use teardown() to destroy the ractive instance, but if you don't ractive will do that automatically as soon as you try to render a new instance into the same container.
That said, it's probably better to have one instance and only update the data. I.e. when the section changes call ractive.set({ selection: 'Profile', prevSelection: 'Home' }).

Related

Vue3 dynamically watching child component data

I'm working in Nuxt3 and I've got a slightly unusual setup trying to watch or retrieve data from child components in a complex form that is structured as a multi-step wizard. It's obviously Vue underneath and I'm using the composition API.
My setup is that I have a page the wizard component is on, and that component has a prop that is an array of steps in the wizard. Each of these steps is some string fields for titles and labels and then a component type for the content. This way I can reuse existing form blocks in different ways. The key thing to understand is that the array of steps can be any length and contain any type of component.
Ideally, I'd like each child component to be unaware of being in the wizard so it can be reused elsewhere in the app. For example, a form that is one of the steps should handle its own validation and make public its state in a way the wizard component can read or watch.
The image below explains my basic setup.
                             
The page includes this tag:
<Wizard :steps="steps" :object="project" #submit="createProject"/>
The Wizard loops over the steps to create each component.
<div v-for="(step) in steps" :key="step.name">
<component v-if="step.status === 'current'" :is="step.content.component" />
</div>
The data to setup the component with the right props for the wizard itself and the child component props.
const steps = ref([
{
name: 'overview',
title: t('overview'),
subTitle: t('projectCreateOverviewDescription'),
status: 'current',
invalid: true,
content: {
component: Overview,
props: null,
model: {}
}
},
{
name: 'members',
title: t('members'),
subTitle: t('projectCreateMembersDescription'),
status: 'upcoming',
invalid: false,
content: {
component: ThumbnailList,
props: {
objects: users,
title: t('users'),
objectNameSingular: t('user'),
objectNamePlural: t('users'),
So far I've tried to dynamically create references in the wizard component to watch the state of the children but those refs are always null. This concept of a null ref seems to be the accepted answer elsewhere when binding to known child components, but with this dynamic setup, it doesn't seem to be the right route.
interface StepRefs {
[key: string]: any
}
let stepRefs: StepRefs = {}
props.steps.forEach(step => {
stepRefs[step.name] = ref(null)
watch(() => stepRefs[step.name].value, (newValue, oldValue) => {
console.log(newValue)
console.log(oldValue)
}, { deep: true })
})
Can anyone direct me to the right approach to take for this setup? I have a lot of these wizards in different places in the app so a component approach is really attractive, but if it comes to it I'll abandon the idea and move that layer of logic to the pages to avoid the dynamic aspect.
To handle changes in child components I'd recommend to use events. You can have the children emit an event on change or completion, and the wizard is listening to events from all children and handling them respectively.
On the wizard subscribe to the event handler of the step component, and process the data coming from each step on completion (or whatever stage you need).
This way you don't need any special data type for the steps, they can just be an array. Simply use a ref to keep track of the current step. You don't even need a v-for, if you just display one step at a time. For a wizard navigation you might still need a v-for, but it would be much simpler. Please see a rough example below.
<div>
<stepComponent step="currentStep" #step-complete="handleStepComplete"/>
<div>
<wizardNavigationItemComponent v-for="step in steps" :active="step.name === currentStep.name" />
</div>
</div>
<script setup lang="ts">
const steps = step[/*your step data here*/]
const currentStepIndex = ref(0)
const currentStep = ref(steps[currentStepIndex.value])
function handleStepComplete(data) {
/* handle the data and move to next step */
currentStepIndex.value = currentStepIndex.value + 1 % steps.length
}
</script>
In the component you just need to define the event and emit it when the data is ready, to pass along the data:
<script setup lang="ts">
const emit = defineEmits<{
(event: "stepComplete", data: <your data type>): void
}>()
/* call emit in the component when its done / filled */
emit("stepComplete", data)
</script>
I hope this helps and can provide a viable path forward for you!

Adding components to existing Ractive instance

I have a somewhat weird question.
In Ractive we can do something like this.
App’s template:
<h1>My app</h1><SubComponent/>
And generally have SubComponent’s template access data from App.
Is there any way to have the same behaviour without mentioning SubComponent in the template?
Something like:
const App = new Ractive({el: ‘#myapp’, …………});
const SubComponent = Ractive.extend({ append: true, ………… });
const example = new SubComponent()
example.render(App.el)
But, with example’s template being able to access App’s data, maybe also giving App the chance to find it by using App.findComponent().
What I’m trying to do, is having unpredictable (= I can’t include them inside templates by default) nested components.
Hopefully this makes sense.
Any idea on how to do it?
I don't know if this will work out for you..
But you can just put a div with a known ID in
<h1>My app</h1><div id="subcomp" />
Then mount your dynamic SubComponent under there.
You can use can event like oncomplete - which will guarentee than div#subcomp has been added to dom.
oncomplete: function() {
this.mycompRef = new SubComponent( { el: '#subcomp' });
// You can skip findComponent and use mycompRef
}

Force rerendering a component

What's the best way to completely teardown and reinstantiate a component in the old one's place, preferably from a template?
Our use case is we have a bunch of Backbone models/collections that are used in our views. In init we might listen to some of those model or collection events (that are sometimes deep), or we may do some sort of setup work relative to that model. It seems we have two options: listen for if the entire model property changes on the view and then unbind any events and bind them to the new model and redo any setup work, or force the view to teardown and put a new one in its place with the new model, since the template may change significantly or even completely. We chose the latter route due to the significance of the change and to ensure we start with a clean slate in the view.
Up to this point we've been wrapping the component in a conditional and changing a boolean to force the old component to teardown and a new one to rerender:
HTML
<p>Some stuff that isn't bound to the model: {{prop1}}, {{prop2}}</p>
{{#if isRenderable}}
<myComponent model="{{model}}" />
{{/if}}
JS
component.set('isRenderable', false); // force `myComponent` to teardown
component.set('model', aDifferentModel); // this often happens in/via template
component.set('isRenderable', true); // force a new `myComponent` to render
Is this a decent approach or are we looking at this all wrong? It seems like there has to be a better option, especially since is necessary in a few places in our app.
One way to do this would be to use the reset() method of the component to change the data, and include a dynamic template function to choose the appropriate template. One of the advantages is that it will not need to re-render the template unless data.type changes. (btw - the design behind the default for components to not re-render is that if the data is updating is more efficient to update the DOM values than to re-render everything. The falsey-block trick works to force a refresh - but that may not always be needed).
There are a lot of details that are specific to your implementation, but this example will give you some ideas:
var Page = Ractive.extend({
template: function(data, t){
return data.type ? t.fromId(data.type) : 'loading...'
}
})
var r = new Ractive({
el: '#container',
template: '#template',
data: { model: datas.person1 },
components: {
page: Page
},
oninit: function(){
var page = this.findComponent('page')
this.observe('model', function(n){
page.reset(n)
})
},
load: function(load){
this.set('model', datas[load])
}
})
This works if there is shared-logic, or no logic, in the component that is rendering the various models.
Often though, you want to use a different component for each model type because there are observers and event handlers specific to that view for that particular model. In that case, this example up-levels the dynamism to the parent and uses an option function for the component:
var r = new Ractive({
el: '#container',
template: '#template',
data: datas.person1,
components: {
page: function(data){
return components[data.type]
}
},
load: function(load){
this.reset( datas[load] )
}
})

EmberJS View programmatically using a not loaded model

I have a model:
App.Checkin = DS.Model.extend({
latitude: DS.attr('string'),
longitude: DS.attr('string'),
time: DS.attr('number')
});
And a route that loads the collection of checkin models (making a request with ember-data) by
model: function() {
return this.store.find('checkin');
}
And then in the template for the route I have
{{view App.MapView}}
And I need to access the model programmatically so that I can iterate over each item in the model to add a pin to the map.
Inside my view I have
didInsertElement: function() {
var data = this.get("context.content");
}
and data is
Class {type: function, store: Class, isLoaded: true, isUpdating: true, toString: function…}
In the network window, the request to the server hasn't completed by that point, so it obviously wouldn't have data to provide. (Even if it did, I don't know how to query an object like that, none of the expected methods worked (get/forEach))
I believe that I need to observe the model being changed, and have tried
updatePins: function() {
debugger;
}.observes('context.content')
inside of the view. I have tried binding to all sorts of things, but reRender has never been called. I've tried the recommendations on Emberjs view binding for Google maps markers
by trying to bind to controller.content, context, App.Checkin, etc.
How do I go about getting the data from the model once it has loaded...inside of the view?
Until the model does not resolve what you get is a promise for that model, obviously the promise does not contain the data just yet but when the request comes back from the server. You could check in your template if the model has data, by observing the model.length property for example using an if helper, the if helper block will re-evaluate when the length property changes this beeing when it has received data.
For example, you could try something like this:
...
{{#if model.length}}
{{view App.MapView}}
{{/if}}
...
This will ensure that your App.MapView is then rendered when your model has data and therefore you will have also access to the data in the view's didInsertElement hook as you'd expect.
Update
Your reRender hook is named slightly wrong, it should be rerender
rerender: function() {
debugger;
}.observes('context.content')
Hope it helps.

Render a Backbone.js collection

I am a Backbone.js n00b and trying to get my head around it. I know how to render a model using a view and the built-in underscore.js templating engine. Now I'm trying to render a collection and that's where I get stuck. There is no server here, so I'm not fetching anything remotely, just a simple HTML page with some JavaScript.
ContinentModel = Backbone.Model.extend({});
ContinentsCollection = Backbone.Collection.extend({
model: ContinentModel,
initialize: function () {
this.continentsView = new ContinentsView;
this.bind("reset", this.continentsView.render);
}
});
ContinentsView = Backbone.View.extend({
el: '#continents',
template: _.template($('#continents-template').html()),
render: function() {
var renderedContent = this.template(this.collection.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
$(function() {
var continentsCollection = new ContinentsCollection();
continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
});
It breaks on the template attribute line in the view but I'm not sure that's where I need to look. Am I supposed to render a collection or do I miss the point completely here (maybe collections are just grouping objects and I shouldn't look at it as a list I can render)?
Thanks for helping...
The problem is that when you define ContinentsView, the template is evaluated and it uses $('#continents-template') - but the DOM is not ready yet, so it does not find the template.
To solve it, simply move the template assignment in the initialize function:
ContinentsView = Backbone.View.extend({
el: '#continents',
initialize: function() {
this.template = _.template($('#continents-template').html());
}
...
Regarding collections, yes, they are grouping objects, specifically sets of models.
You should make the code so the models (and collections) do NOT know about the views, only the views know about models.
ContinentModel = Backbone.Model.extend({});
ContinentsCollection = Backbone.Collection.extend({
model: ContinentModel,
// no reference to any view here
});
ContinentsView = Backbone.View.extend({
el: '#continents',
initialize: function() {
this.template = _.template($('#continents-template').html());
// in the view, listen for events on the model / collection
this.collection.bind("reset", this.render, this);
},
render: function() {
var renderedContent = this.template(this.collection.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
$(function() {
var continentsCollection = new ContinentsCollection();
continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
// initialize the view and pass the collection
var continentsView = new ContinentsView({collection: continentsCollection});
});
It is also worth noting there are additional complexities that quickly rear their heads when rendering a collection in a view. For instance, the view generally needs to be re-rendered when models are added or removed from the collection. It isn't rocket science to implement your own solution, but it is probably worth looking into existing solutions since there are quite a few tried and tested ones out there.
Backbone.CollectionView is a robust collection view class that handles selecting models in response to mouse clicks, reordering the collection based on drag and drop, filtering visible models, etc.
Several popular frameworks built on top of backbone also provide simple collection view classes, like Backbone.Marionette, Chaplin, and Layout Manager.
Even though Backbone itself does not provide any structure for rendering a collection, it is a non-trivial problem and lots of people have different opinions on how it should be done. Luckily it is such a common need that there are quite a few good options already in the eco system.

Resources