I have 3 routes: items/one, items/two, and items/three and they're all pointing to 'items' vm/view.
in the items.js activate function, I'm checking the url, and based on that, I'm changing a filter:
function activate(r) {
switch (r.routeInfo.url) {
case 'items/one': vm.filterType(1); break;
case 'items/two': vm.filterType(2); break;
case 'items/three': vm.filterType(3); break;
}
return init(); //returns a promise
}
The items view has a menu with buttons for one, two, and three.
Each button is linked to an action like this:
function clickOne() {
router.navigateTo('#/items/one');
}
function clickTwo() {
router.navigateTo('#/items/two');
}
function clickThree() {
router.navigateTo('#/items/three');
}
this all works and I get the right filter on the view. However, I've noticed that if I'm on 'one', and then go to 'two', the ko-bound variables update in 'real-time', that is, as they're changing, and before the activate promise resolves, which causes the transition to happen twice (as the data is being grabbed, and after the activate function returns).
This only happens in this scenario, where the view and viewmodel are the same as the previous one. I'm aware that this is a special case, and the router is probably handling the loading of the new route with areSameItem = true. I could split the VMs/Views into three and try to inherit from a base model, but I was hoping for a simpler solution.
I was able to solve the issue by simply removing the ko bindings before navigation using ko.cleanNode() on the items containing div.
Assuming that in your parent view you've a reference to router.activeItem with a transition e.g.
<!--ko compose: {model: router.activeItem,
afterCompose: router.afterCompose,
transition: 'entrance'} -->
<!--/ko-->
then the entrance transition happens on every route you've setup to filter the current view.
But this transition should probably only happen on first time visit and from that point on only the view should be updated with the filtered data. One way to accomplish that would be to setup an observable filterType and use filterType.subscribe to call router.navigateTowith the skip parameter.
Something along the line:
var filterType = ko.observable();
filterType.subscribe(function (val) {
// Create an entry in the history but don't activate the new route to prevent transition
// router plugin expects this without leading '/' dash.
router.navigateTo(location.pathname.substring(1) + '#items/' + filterType(), 'skip');
activate();
});
Please note that the router plugin expects skipRouteUrl without leading / slash to compare the context.path. https://github.com/BlueSpire/Durandal/blob/master/App/durandal/plugins/router.js#L402
Your experience might be different.
Last in order to support deep linking in activate:
function activate(routerdata) {
// deep linking
if (routerdata && routerdata.filterType && (routerdata.filterType !== filterType() ) ) {
filterType(routerdata.filterType);
}
return promise;
};
Related
I am creating a simple inventory system that will have various categories for the items, as well as the option to display all items.
Going from the 'all' category to the 'general' category will remove the unnecessary item, but leaves a gap for a significant period of time and there is not animation of the item after the gap sliding into place.
I am doing this using Vuejs and vue2-animate.
computed:
{
active_items: function()
{
var _self = this;
if(_self.active_category === 'all')
{
return _self.items;
} else
{
return _self.items.filter(function(i)
{
return i.category === _self.active_category;
});
}
}
},
https://jsfiddle.net/Crotanite/cn07tmho/8/
The gap that is left in place of disappearing list items is because an element that transition is being applied to, stays in place until leave-active animation phase is finished.
Simple fix, is to add position: absolute; to a leaving element. This will allow sibling list items to take it's position.
Below is updated version of your example with additional class zoomOut__absolute added to leave-active-class attribute. Additional class is added to avoid overwriting styles of animate.css:
JSFiddle
I'm having a look at Vue.js with a view to simplifying an application which is starting to get a bit too complex with jQuery. I want to utilise the data binding so that the state of an 'Order' object automatically enables or disables certain buttons (e.g., I want the submit button to be automatically disabled unless an order, containing items, exists). I have something which partly works, with this declaration:
var content = new Vue({
el: '#content',
computed: {
orderExists: function () {
return (shopOrder != null && !isEmpty(shopOrder.items));
}
}
});
I use it in a button like this:
<button type="button" id="btnDisplay" v-bind:disabled="!orderExists">Show Selected</button>
On page load, the buttons using this technique are indeed enabled/disabled correctly. However, when I add items to the order object, thereby changing its state, I'm not seeing any update in the buttons' states - they should be being enabled.
I assume I'm misunderstanding something basic about how this works with Vue.js, as I've only spent a couple of hours with it, so any help would be appreciated.
Hmmm why not pass the property as reactive data?
You can do something like:
...
computed: {
orderExists: function () {
this.disabled = (shopOrder != null && !isEmpty(shopOrder.items));
}
}
Fiddle.
DP: the example is in Vue 2
The issue is that Vue has to manage your data objects in order to set them up in a way where it can observe the changes to them (i.e. be made reactive). This is done by specifying the data option to your Vue creation. Something like:
data: {
shopOrder: null
}
Then update your code like this:
orderExists: function () {
return (this.shopOrder != null && !isEmpty(this.shopOrder.items));
}
And of course at some point you need to set this.shopOrder to a valid order object.
This was originally posted on discuss.emberjs.com. See:
http://discuss.emberjs.com/t/what-is-the-proper-use-of-store-filter-store-find-for-infinite-scrolling/3798/2
but that site seems to get worse and worse as far as quality of content these days so I'm hoping StackOverflow can rescue me.
Intent: Build a page in ember with ember-data implementing infinite scrolling.
Background Knowledge: Based on the emberjs.com api docs on ember-data, specifically the store.filter and store.find methods ( see: http://emberjs.com/api/data/classes/DS.Store.html#method_filter ) I should be able to set the model hook of a route to the promise of a store filter operation. The response of the promise should be a filtered record array which is a an array of items from the store filtered by a filter function which is suppose to be constantly updated whenever new items are pushed into the store. By combining this with the store.find method which will push items into the store, the filteredRecordArray should automatically update with the new items thus updating the model and resulting in new items showing on the page.
For instance, assume we have a Questions Route, Controller and a model of type Question.
App.QuestionsRoute = Ember.Route.extend({
model: function (urlParams) {
return this.get('store').filter('question', function (q) {
return true;
});
}
});
Then we have a controller with some method that will call store.find, this could be triggered by some event/action whether it be detecting scroll events or the user explicitly clicking to load more, regardless this method would be called to load more questions.
Example:
App.QuestionsController = Ember.ArrayController.extend({
...
loadMore: function (offset) {
return this.get('store').find('question', { skip: currentOffset});
}
...
});
And the template to render the items:
...
{{#each question in controller}}
{{question.title}}
{{/each}}
...
Notice, that with this method we do NOT have to add a function to the store.find promise which explicitly calls this.get('model').pushObjects(questions); In fact, trying to do that once you have already returned a filter record array to the model does not work. Either we manage the content of the model manually, or we let ember-data do the work and I would very much like to let Ember-data do the work.
This is is a very clean API; however, it does not seem to work they way I've written it. Based on the documentation I cannot see anything wrong.
Using the Ember-Inspector tool from chrome I can see that the new questions from the second find call are loaded into the store under the 'question' type but the page does not refresh until I change routes and come back. It seems like the is simply a problem with observers, which made me think that this would be a bug in Ember-Data, but I didn't want to jump to conclusions like that until I asked to see if I'm using Ember-Data as intended.
If someone doesn't know exactly what is wrong but knows how to use store.push/pushMany to recreate this scenario in a jsbin that would also help too. I'm just not familiar with how to use the lower level methods on the store.
Help is much appreciated.
I just made this pattern work for myself, but in the "traditional" way, i.e. without using store.filter().
I managed the "loadMore" part in the router itself :
actions: {
loadMore: function () {
var model = this.controller.get('model'), route = this;
if (!this.get('loading')) {
this.set('loading', true);
this.store.find('question', {offset: model.get('length')}).then(function (records) {
model.addObjects(records);
route.set('loading', false);
});
}
}
}
Since you already tried the traditional way (from what I see in your post on discuss), it seems that the key part is to use addObjects() instead of pushObjects() as you did.
For the records, here is the relevant part of my view to trigger the loadMore action:
didInsertElement: function() {
var controller = this.get('controller');
$(window).on('scroll', function() {
if ($(window).scrollTop() > $(document).height() - ($(window).height()*2)) {
controller.send('loadMore');
}
});
},
willDestroyElement: function() {
$(window).off('scroll');
}
I am now looking to move the loading property to the controller so that I get a nice loader for the user.
I have a SPA in which I am using Durandal / KnockoutJS with knockout.validation.js. Inside the {view}.js I have this set
ko.validation.configure ({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: false,
messageTemplate: null,
parseInputAttributes: true,
});
and inside one of the views I have
<input class="input-member"
type="text"
data-bind="value: memberno, validationOptions: { errorElementClass: 'input-validation-error' }"/>
When the view is first activated the element correctly has the style input-validation-error applied.
On subsequent loading of the view the css is not applied as I require. I can see in firebug that the input field now has this class applied input-member validationElement
I don't know where validationElement came from - but something got messed up with the knockout bindings. I have tried moving the validation config into the shell.js but the result is the same (and not a good idea anyway).
Edit:
So far looks like errorElementClass: 'input-validation-error' is not being reapplied to the element after navigation. If the field is modified-focused-cleared , the validation fires normally. validationElement is the placeholder for the errorElementClass
Update
Found this bit of info at the github site and seems to be what im after
in {view}.js
function activate() {
vm.memberno.isModified(false);
return true;
}
The above code seems to work for input fields but not for select fields. Another idea I'm looking at is adding a binding handler like so
ko.bindingHandlers.validationElement = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var valueIsValid = valueAccessor().isValid();
if (!valueIsValid) {
$(element).addClass("input-validation-error");
} else {
$(element).removeClass("input-validation-error");
}
}
}
which works for all selects and inputs but is always on. If there's a way to deactivate this binding until the first form submit fires I think that will do it.
There needs to be a way to re-apply the binding or cause the binding to update. Try putting some code in the view model's activate function that forces validation.
I need help in dynamically adding/removing route in Durandal Router. What I want is after user is logged in then I would be able to add or remove specific route depending upon logged in user's type.
I tried to add/remove route from visibleRoutes/allRoutes array ... but get binding exception from knockout library...
I was hoping it would be common scenario... but still couldn't find any solution ... please help me in fixing this issue.
Thanks.
Wasim
POST COMMENTS:
I tried this function to dynamically hide/show route... and similary tried to add/remove route from allRoutes[] ... but then get exception on knockout bidning
showHideRoute: function (url,show) {
var routeFounded = false;
var theRoute = null;
$(allRoutes()).each(function (route) {
if (url === this.url) {
routeFounded = true;
var rt = this;
theRoute = rt;
return false;
}
});
if (routeFounded)
{
if (show)
{
visibleRoutes.push(theRoute);
}
else
{
visibleRoutes.remove(theRoute);
}
}
}
In Durandal 2.0.
You can enumerate the routes to find the one you wish to show/hide.
Then change the value of: nav property
Then run buildNavigationModel();
here is an example:
// see if we need to show/hide 'flickr' in the routes
for (var index in router.routes) {
var route = router.routes[index];
if (route.route == 'flickr') {
if (vm.UserDetail().ShowFlickr) { // got from ajax call
// show the route
route.nav = true; // or 1 or 2 or 3 or 4; to have it at a specific order
} else if (route.nav != false) {
route.nav = false;
}
router.buildNavigationModel();
break;
}
}
Durandal 2.0 no longer has the method visibleRoutes. I found that the following works for me.
router.reset();
router.map([
{ route: 'home', moduleId: 'home/index', title: 'Welcome', nav: true },
{ route: 'flickr', moduleId: 'flickr/index', title: '', nav: true }
])
.buildNavigationModel()
.mapUnknownRoutes('home/index', 'not-found');
This removes all previous routes, if you want to maintain current routes you could try using the router.routes property to rebuild the array of routes.
I had a similar requirement. If I were you, I would take another approach. Rather than adding/removing routes when application loads - get the right routes to begin with per user type.
Two options, (I use both)
1) have a json service provide the proper routes per user type, this approach would be good if you need to 'protect/obscure' routes... i.e. I don't want the route referenced on any client resource.
2) A simpler solution see Durandal.js: change navigation options per area
You can have a settings property identify the user type.
I hope this helps.
I had a similar problem: First, router.visibleRoutes() is an observable array. In other words, when you change its value, the routes automatically update. However, the items in this array are not observable, so to make a change you need to replace the entire array and not just make a change to a single item in it.
So, all you have to do is find which item in this array you want to remove, and then create a new array without this item, and set router.visibleRoutes() to this new array.
If, for example, you find out the it is the 3rd item, then one way of doing it is:
router.visibleRoutes(router.visibleRoutes().splice(2, 1))
Note that splice() returns a new array where an item is removed. This new array is put into router.visibleRoutes.